<template>
  <Teleport :to="'#' + code.id" :disabled="moveDisabled">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>
            {{ code.id }} &nbsp; &nbsp;
            <el-button type="" @click="start">运行</el-button>
          </span>
          <el-button class="button" type="text" @click="showCode"
            >编辑代码</el-button
          >
        </div>
      </template>
      <transition name="el-zoom-in-top">
        <el-row :gutter="10" v-show="isShowCode">
          <el-col :span="12">
            template：
            <el-input v-model="code.template" v-bind="tempProps"></el-input>
          </el-col>
          <el-col :span="12">
            setup：
            <el-input v-model="code.js" v-bind="jsProps"></el-input>
          </el-col>
        </el-row>
      </transition>
      <hr />
      <el-row :gutter="10">
        <el-col :span="24">
          <div style="min-height: 200px; margin-top: 10px; margin-bottom: 10px">
            <run-code :reload="reload" :code="code"> </run-code>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </Teleport>
</template>

<script>
import { watch, ref } from "vue";
import { ElInput, ElButton, ElRow, ElCol, ElCard } from "element-plus";
import runCode from "./run-cdn.vue";

const jsProps = {
  // autosize: true,
  rows: 10,
  type: "textarea",
  placeholder: "const foo = ref('测试') \nreturn {\n foo \n}",
};

const tempProps = {
  // autosize: true,
  rows: 10,
  type: "textarea",
  placeholder: "可以写 template ",
};

const idProps = {
  // autosize: true,
  type: "text",
  placeholder: "编写代码标识，用于转移位置",
};
</script>

<script setup>
let code = ref({
  id: "演示ref的使用方式",
  isRun: false,
  js: "const foo = ref(11)\nconsole.log(foo)\nconst myadd = () => {\n  foo.value += 1\n}\n\nreturn {\n  foo,\n  myadd\n}",
  template:
    'ref: {{foo}}\n<br>\n<br>\n<el-button @click="myadd">按钮</el-button>\n',
  style: "",
});
// 控制刷新运行代码
const reload = ref(false);
const start = () => {
  reload.value = !reload.value;
};

// 设置代码的显示和隐藏
const isShowCode = ref(false);
const showCode = () => {
  isShowCode.value = !isShowCode.value;
};

// 是否穿越
const moveDisabled = ref(true);
watch(
  () => code.id,
  (id) => {
    if (id) {
      // 检测是否有对应的div
      const show = document.getElementById(id);
      if (show) {
        show.innerHTML = "";
        moveDisabled.value = false;
      } else moveDisabled.value = true;
    }
    reload.value = !reload.value;
  },
  { immediate: true }
);
</script>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 100%;
}
</style>
